<template>
  <el-drawer v-model="dialogVisible" title="导出订单" size="40%">
    <el-form :model="form">
      <el-form-item label="订单类型">
        <el-select v-model="form.tab" placeholder="请选择">
          <el-option
            v-for="item in tabs"
            :key="item.status"
            :label="item.name"
            :value="item.status"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="onSubmit" :loading="loading"
          >导出</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script setup>
import { reactive, ref } from "vue";
import { toast } from "../../composables/util";
import { getExport } from "~/api/order.js";
defineProps({
  tabs: Array,
});

const form = reactive({
  tab: null,
  time: "",
});
const dialogVisible = ref(false);

const open = () => (dialogVisible.value = true);

const close = () => (dialogVisible.value = false);
const loading = ref(false);
const onSubmit = () => {
  if (!form.tab) return toast("订单类型不能为空", "error");
  loading.value = true;
  let starttime = null;
  let endtime = null;
  if (form.time && Array.isArray(form.time)) {
    starttime = form.time[0];
    endtime = form.time[1];
  }
  getExport({
    tab: form.tab,
    starttime,
    endtime,
  })
    .then((data) => {
      window.open(`https://testapi.bscd8.com/storage/excel/${data}`, "_blank");

      close();
    })
    .finally(() => {
      loading.value = false;
    });
};

function downloadFile(res, fileName) {
  let blob = new Blob([res]); //res为从后台返回的数据
  if (!fileName) {
    fileName = res.headers["content-disposition"].split("filename=").pop();
  }
  if ("msSaveOrOpenBlob" in navigator) {
    window.navigator.msSaveOrOpenBlob(blob, fileName);
  } else {
    const elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  }
}
defineExpose({
  open,
});
</script>
